<template>
  <section>
    <el-row v-show="pageOne">
      <el-form :inline="true" size="mini">
        <el-form-item label="选择公司：" >
          <el-select v-model="companyId" placeholder="请选择">
            <el-option v-for="company in companies" :key="company.id" :label="company.companyName" :value="company.id"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </el-row>
    <el-row v-show="pageOne">
      <!--搜索-->
      <el-col :span="20">
        <el-form :inline="true" size="mini" ref="form">
          <el-form-item label="选择医院：">
            <!--医院列表-选择-->
            <el-select v-model="selDepartment" placeholder="请选择">
              <el-option v-for="department in departments" :key="department.id" :label="department.name" :value="department.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <!--时间选择-->
            <el-date-picker v-model="selWeekStart" type="week" format="yyyy 第 WW 周 MM 月 dd 日" placeholder="选择周">
            </el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button @click="showAddSchedule">
              <icon name="plus"></icon>
            </el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>

    <el-row v-show="pageOne">
      <el-table :data="scheduleList" border style="width: 100%">
        <el-table-column type="index" width="50">
        </el-table-column>
        <el-table-column label="周次" prop="title" >
        </el-table-column>
        <el-table-column label="开始日期" prop="start" :formatter="formatDate" >
        </el-table-column>
        <el-table-column label="结束日期" prop="end" :formatter="formatDate">
        </el-table-column>
        <el-table-column label="操作" width="220" fixed="right">
          <template slot-scope="scope">
            <el-button :type="scope.row.edit?'success':'primary'" @click='confirm(scope)' size="mini" icon="edit">{{scope.row.edit?'完成':'编辑'}}</el-button>
            <el-tooltip content="导入到挂号">
              <el-button type="primary" size="mini" @click="importToGoods(scope)">导入</el-button>
            </el-tooltip>
            <el-button type="danger" @click='del(scope)' size="mini" >DEL</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-row>

    <el-row v-if="!pageOne">
      <el-table  :data="scheduleItemTable" style="width: 100%">
        <el-table-column>
          <el-table-column prop="departmentName" label="医院">
          </el-table-column>
          <el-table-column prop="sectionName" label="科室">
          </el-table-column>
        </el-table-column>
        <el-table-column v-for="(date,i1) in selWeek" :key="date.text" :label="date.text">
          <el-table-column :label="date.day">
            <el-table-column v-for="(ban,i2) in date.bans" :key="ban" :label="ban">
              <template slot-scope="scope">
                <div @click="showAddDialog(scope.row,i1,i2)"  style="border: 0px solid crimson; min-height: 50px;cursor:pointer">
                  <div v-if="scope.row.repertories[i1*2+i2].length>0">
                    <div v-for="(b,i3) in scope.row.repertories[i1*2+i2]" class="item-box">
                      <div class="icon" @click.stop="remove(b.id)">
                        <icon name="times" width="16" height="16"></icon>
                      </div>
                      <span>{{b.name?b.name:'???'}}</span>
                    </div>
                  </div>
                </div>
              </template>
            </el-table-column>
          </el-table-column>
        </el-table-column>
      </el-table>
      <el-row>
        <el-button type="success" icon="el-icon-check" circle style="margin-top: 20px" @click="confirmSchedule"></el-button>
      </el-row>
    </el-row>

    <el-dialog title="选择新建排班条件" :visible.sync="showAdd" >
      <el-form :inline="true" size="mini" ref="form">
        <el-form-item label="选择公司：" >
          <el-select v-model="companyId" placeholder="请选择">
            <el-option v-for="company in companies" :key="company.id" :label="company.companyName" :value="company.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="选择医院：">
          <!--医院列表-选择-->
          <el-select v-model="selDepartment" placeholder="请选择">
            <el-option v-for="department in departments" :key="department.id" :label="department.name" :value="department.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="选择周次：">
          <!--时间选择-->
          <el-date-picker v-model="selWeekStart" type="week" format="yyyy 第 WW 周 MM 月 dd 日" placeholder="选择周">
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button @click="addSchedule">
            <icon name="regular/check-circle"></icon>
          </el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <el-dialog title="坐诊安排" :visible.sync="showDialog" width="480px">
      <el-form size="small" style="padding:0 40px;margin:0 auto;" label-width="80px">
        <el-form-item label="坐诊医生:">
          <el-select v-model="selDocForm.docId" placeholder="请选择医生">
            <el-option v-for="doctor in doctors" :label="doctor.name" :value="doctor.id" :key="doctor.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="addDoctor">提交</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-dialog title="导入到挂号" :visible.sync="showImportDialog" width="600px">
      <!--<el-row style="height:30px;line-height:30px;">-->
        <!--<el-col :span="4">选择分类</el-col>-->
        <!--<el-col :span="20">-->
          <!--<el-select v-model="goodsTypeId" size="mini">-->
            <!--<el-option v-for="gt in goodsTypes" :key="gt.id" :value="gt.id" :label="gt.name"></el-option>-->
          <!--</el-select>-->
        <!--</el-col>-->
        <!--<el-col>-->
          <!---->
        <!--</el-col>-->
      <!--</el-row>-->
      <el-row>
        <label>{{importMessage}}</label>
      </el-row>
      <el-row>
        <el-progress :text-inside="true" :stroke-width="18" :percentage="importPercentage"></el-progress>
      </el-row>
    </el-dialog>
  </section>
</template>

<script>
  import {mapGetters, mapActions, mapMutations} from 'vuex'
  import DateUtils from '@/common/DateUtils'
  import DateFormat from '@/common/date-formater'
  import errHandler from '@/assets/errHandler.js'

  export default {
    name: "schedule",
    data() {
      return {
        doctors:[],
        companies:[],
        companyId:null,
        pageOne:true,
        selDepartment: null,
        selWeekStart: null,
        scheduleList:[],
        showAdd:false,
        showDialog:false,
        showImportDialog:false,
        departments:[],
        selWeek:[],
        scheduleItemTable:null,
        title:null,
        selDocForm:{
          sectionId:null,
          date:null,
          time:null,
          docId:null,
        },
        currentSchedule:null,
        importMessage:'',
        importPercentage:0,
        goodsTypes:null,
        goodsTypeId:1
      }
    },
    created() {
      //加载公司列表，用来选择
      this.loadCompanyList()
      //加载医生列表
      this.getCustomerList(5)
      //加载商品列表
      // this.fetch({name:'getGoodsTypeList'}).then(res=>{
      //   this.goodsTypes = res
      // }).catch(err=>{
      //   errHandler.handle(this,err)
      // })
    },
    watch: {
      companyId(nv,ov){
        if(nv){
          this.loadDepartments(nv)//加载该公司下部门类型为医院的部门
        }
      },
      selWeekStart(nv, ov) {
        this.selWeek.splice(0, this.selWeek.length)
        this.title = DateUtils.getWeekNumber(nv)
        //查询
        if(this.selDepartment){
          //如果已经选中医院，再选时间，显示该医院下该周的排班

        }
        //新建 //制作新的 weeks
        for (let i = -1; i < 6; i++) {
          let mc = nv.getTime()
          let sec = DateUtils.addDays(mc, i)
          let day = DateUtils.getDay(sec)
          let tmp = {text: DateUtils.format(sec, 'yyyy-MM-dd'), day, bans: ['上午', '下午'], index: i}
          this.selWeek.push(tmp)
        }
      },
      selDepartment(nv, ov) {//得到医院部门id
        if (nv) {
          //新建排班
          this.loadSections(nv)//获取科室列表
          //查询
          this.loadScheduleList(nv)//获取排班列表
        }
      }
    },
    methods: {
      ...mapActions({
        fetch: 'fetch'
      }),
      importToGoods(scope){
        console.log(scope)
        this.showImportDialog = true
        this.importPercentage = 10
        //制作商品信息
        this.importMessage = "导入挂号 第["+scope.row.title+"]预约挂号 商品信息"
        //参数组装
        let params = {goodsTypeId:1,name:"第["+scope.row.title+"]周预约挂号",departmentId:this.selDepartment}
        params.data = {
          type:'register',
          startDate:scope.row.start,
          endDate:scope.row.end,
          departmentId:scope.row.departmentId,
          departmentName:scope.row.departmentName,
          scheduleId:scope.row.id

        }
        this.fetch({name:'createGoods',data:params})
          .then(res=>{
            //成功之后
            this.importPercentage = 40
            this.importMessage = "导入挂号 名目信息"
            let perSpan = 60/scope.row.scheduleItems.length
            //规格
            this.createGoodsSku(res,scope.row.scheduleItems,perSpan)
          }).catch(err=>{
            errHandler.handle(this,err)
        })
        //制作规格信息
      },
      createGoodsSku(goods,items,perSpan){
        let tmpItem = items.shift()
        let params = {}
        params.goodsId = goods.id
        params.price = tmpItem.section.basePrice
        this.fetch({name:'createSn',data:{snType:4}}).then(res=>{
          params.sn =res.sn
        }).catch(err=>{
          console.log(err)
        })
        //日期，时间，科室，医生
        params.props = ""
        params.props += "日期:"+DateFormat.format(tmpItem.date)+";"
        params.props += "时间:"+(tmpItem.time === "1" ? "上午":"下午")+";"
        params.props += "科室:"+tmpItem.section.name+";"
        params.props += "医生:"+tmpItem.doctorName
        //data很重要
        params.data = {
          date:tmpItem.date,
          time:tmpItem.time,
          sectionId:tmpItem.section.id,
          sectionName:tmpItem.section.name,
          doctorId:tmpItem.doctorId,
          doctorName:tmpItem.doctorName
        }
        this.importMessage = "导入挂号 名目:"+params.props
        this.fetch({name:'createGoodsSku',data:params}).then(res=>{
          //设置进度条
          this.importPercentage+=perSpan
          //下一个
          if(items.length>0)
            this.createGoodsSku(goods,items,perSpan)
          else {
            this.importMessage = "导入挂号信息成功"
            this.importPercentage == 100
            setTimeout(()=>{
              this.showImportDialog = false
            },3000)
          }
        }).catch(err=>{
          console.log(err)
          errHandler.handle(this,err)
        })
      },
      loadCompanyList(){
        //加载公司列表
        this.fetch({name:"getCompanyList"})
          .then((res)=>{
            if(res.errCode){
              this.$message({type:'info',message:res.errMsg})
            }else{
              console.log(res)
              this.companies = res
            }
          })
          .catch((err)=>{
            console.log(err)
            this.$message({type:'error',message:"服务器错误"})
          })
      },
      loadDepartments(companyId){
        console.log(companyId)
        this.fetch({name:"getDepartmentList",data:{companyId}})
          .then(res=>{
            if(res.errCode){
              this.$message({type:'error',message:res.errMsg})
            }else{
              console.log(res)
              // for(let i=0;i<res.length;i++){
              //   res[i].departmentTypeId = res[i].departmentType.id
              // }
              this.departments=res
            }
          })
          .catch(err=>{
            console.log(err)
            this.$message({type:'error',message:'服务器错误'})
          })
      },
      test(){
        console.log(this.pageOne)
        this.pageOne =!this.pageOne
        console.log(this.pageOne)
      },
      getCustomerList(groupId){
        this.fetch({name:"getCustomerList",data:{groupId}})
          .then((res)=>{
            if(res.errCode){
              this.$message({type:'info',message:res.errMsg})
            }else{
              // console.log(res)
              // for(let i=0;i<res.length;i++){
              //   let tmp = res[i]
              //   this.doctors.push({doctor:tmp,amount:''})
              // }
              this.doctors = res
            }
          })
          .catch((err)=>{
            console.log(err)
            this.$message({type:'error',message:"服务器错误"})
          })
      },
      formatDate(row, column, cellValue, index){
        return DateFormat.format(cellValue)
      },
      loadHospitals(){//加载医院列表，用于选择
        this.fetch({name: "getHospitalList"})
          .then((res) => {
            if (res.errCode) {
              this.$message({type: 'info', message: res.errMsg})
            } else {
              // console.log(res)
              this.hospitals = res
            }
          })
          .catch((err) => {
            console.log(err)
            this.$message({type: 'error', message: "服务器错误"})
          })
      },
      loadScheduleList(departmentId){//获取排班列表
        console.log(departmentId)
        this.fetch({name: "getScheduleList",data:{departmentId,page:0}})
          .then((res) => {
            if (res.errCode) {
              this.$message({type: 'info', message: res.errMsg})
            } else {
              this.scheduleList = res.content
              console.log(res)
            }
          })
          .catch((err) => {
            console.log(err)
            this.$message({type: 'error', message: "服务器错误"})
          })
      },
      showAddSchedule(){//跳出对话框——新建排班选择条件
        this.showAdd = true
      },
      addSchedule(){//增加一个排班        //先判断能否增加，增加条件，科室列表和周次，且周次不重复
        if(this.sections && this.selWeek){
          let newTitle = this.title
          //在排班表里找title
          let index = this.scheduleList.findIndex(i => i.title === newTitle)
          if(index >= 0 ){//存在该周次的排班，不能增加排班
            this.$message('本周排班已存在')
          }else {
            //可以新建了，更新数据库
            this.fetch({name:"createSchedule",data:{title:this.title,
                departmentId:this.selDepartment,
                start:this.selWeek[0].text,
                end:this.selWeek[this.selWeek.length-1].text}})
              .then((res)=>{
                console.log(res)
                //更新查询页面的排班列表
                this.scheduleList.push(res)
                //关闭对话框
                this.showAdd = false
              })
              .catch((err)=>{
                console.log(err)
                errHandler.handle(this.err)
              })
          }
        }else {
          //条件不满足
          this.$message('请选择医院及时间')
        }
      },
      loadSections(departmentId){//通过医院部门获取科室
        console.log(departmentId)
        this.fetch({name: "getHisSectionList", data: {departmentId:departmentId}})
          .then(res => {
            console.log(res)//科室列表
            this.sections = res
          }).catch(err => {
            console.log(err)
            errHandler.handle(this.err)
        })
      },
      confirm(scope){//确认编辑按钮
        this.currentSchedule = scope.row
        this.loadSections(this.currentSchedule.departmentId)//加载该周排班医院下的科室
        if(this.sections){
          console.log(this.sections)
          this.selWeek = []
          for (let i = 0; i < 7; i++) {//加载该周时间段
            let sec = DateUtils.addDays(this.currentSchedule.start, i)
            let day = DateUtils.getDay(sec)
            let tmp = {text: DateUtils.format(sec, 'yyyy-MM-dd'), day, bans: ['上午', '下午'], index: i}
            this.selWeek.push(tmp)
          }
          //点击之后要跳出编辑对话框
          //判断是否能够编辑
          if(this.currentSchedule.achieve || this.currentSchedule.deleted){//已完成或删除
            this.$message('本周排班已确认或已删除，不能编辑')
          }else {
            //能，页面更新
            this.scheduleItemTable = []
            this.pageOne = false
            console.log(this.sections)
            this.sections.forEach(d => { //循环科室列表，做一个空白的排班表
              let data = {
                departmentName: d.departmentName,
                sectionId: d.id,
                sectionName: d.name,
                repertories: [[],[],[],[],[],[],[],[],[],[],[],[],[],[]]
              }
              this.scheduleItemTable.push(data)
            })
            if(this.currentSchedule.scheduleItems && this.currentSchedule.scheduleItems.length >0){
              this.getSecheduleItem()
            }
          }
        }
      },
      getSecheduleItem(){//获取已有排班项
        console.log(this.currentSchedule.scheduleItems)
        this.currentSchedule.scheduleItems.forEach(s => {//循环该排班内的排班项，非空白的排班表，填进内容
          //查找科室
          let section = this.sections.find(d => d.id === s.section.id)//找到有记录的排班科室
          if (section) {//如果科室存在
            let dIndex = this.scheduleItemTable.findIndex(i => i.sectionId === section.id)//找到这个排班项的索引值
            let theObj = this.scheduleItemTable[dIndex]//找到这个排班项
            //计算14个时间段
            let day = DateUtils.parseDate(DateFormat.format(s.date)).getDay()
            let time = s.time === '1' ? 0 : 1
            let colIndex = day * 2 + time
            let theRep = theObj.repertories[colIndex]
            //加医生了
            theRep.push({id: s.id, name: s.doctorName})
          }
        })
      },
      del(scope){//删除该周排班
        //判断是否能够删除
        console.log(scope.row.id)
        this.fetch({name:"delSchedule",data:{id:scope.row.id}})
          .then((res)=>{
            if(res.errCode){
              this.$message({type:'info',message:res.errMsg})
            }else{
              console.log(res)
              console.log(this.scheduleList)
              this.scheduleList.splice(scope.$index,1)
            }
          })
          .catch((err)=>{
            console.log(err)
            this.$message({type:'error',message:"服务器错误"})
          })
      },
      showAddDialog(row,date,time){//跳出编辑排班项的对话框
        console.log(this.selDocForm)
        console.log(row)
        // console.log(ii)//0~6,周日~周一
        // console.log(i2)//0~1,上午，下午
        this.pos = date*2+time
        console.log(this.pos)
        this.selDocForm.sectionId = row.sectionId
        this.selDocForm.date = this.selWeek[date].text
        if(time === 0){
          this.selDocForm.time = '1'
        }else if(time === 1){
          this.selDocForm.time = '2'
        }
        this.showDialog = true

      },
      addDoctor(){//增加医生排班项
        console.log(this.selDocForm)
        let data ={date:this.selDocForm.date, time:this.selDocForm.time, sectionId:this.selDocForm.sectionId, doctorId:this.selDocForm.docId, scheduleId:this.currentSchedule.id}
        console.log(data)
        this.fetch({name:"creatSecheduleItem",data:data})
          .then((res)=>{
            if(res.errCode){
              console.log(res)
              this.$message({type:'info',message:res.errMsg})
            }else{
              console.log(res)
              let index = this.sections.findIndex(i => i.id === res.section.id)
              this.scheduleItemTable[index].repertories[this.pos].push({id:res.id,name:res.doctorName})
              this.currentSchedule.scheduleItems.push(res)
              console.log(this.scheduleItemTable)
              console.log(this.currentSchedule)
              this.showDialog = false
              console.log(this.scheduleItemTable)
            }
          })
          .catch((err)=>{
            console.log(err)
            this.$message({type:'error',message:"服务器错误"})
          })
      },

      remove(sid){//---------------------------删除排班项
        this.fetch({name:"delSecheduleItem",data:{id:sid}})
          .then((res)=>{
            if(res.errCode){
              this.$message({type:'info',message:res.errMsg})
            }else{
              //数据库内容删除
              //更新页面显示
              for(let i=0;i<this.scheduleItemTable.length;i++){
                let i1=this.scheduleItemTable[i].repertories
                for(let j=0;j<i1.length;j++){
                  let j1 = i1[j]
                  let index = j1.findIndex(n => n.id === sid)
                  if(index>=0){
                    this.scheduleItemTable[i].repertories[j].splice(index,1)
                    let uIndex = this.currentSchedule.scheduleItems.findIndex(u => u.id === sid)
                    this.currentSchedule.scheduleItems.splice(uIndex,1)
                    return
                  }
                }
              }
            }
          })
          .catch((err)=>{
            console.log(err)
            this.$message({type:'error',message:"服务器错误"})
          })
      },
      confirmSchedule(){
        console.log(this.currentSchedule)
        //确定排班完毕
        this.fetch({name: "updateSchedule",data:{id:this.currentSchedule.id}})
          .then((res) => {
            if (res.errCode) {
              this.$message({type: 'info', message: res.errMsg})
            } else {
              console.log(res)
              this.pageOne = true
            }
          })
          .catch((err) => {
            console.log(err)
            this.$message({type: 'error', message: "服务器错误"})
          })
      }
    }
  }
</script>

<style lang="scss">

  .item-box{
    position: relative;
    line-height:24px;
    border:0px solid #777;
    .icon{
      width:16px;
      height:16px;
      color: red;
      top:3px;
      right: -10px;
      position: absolute;
      display: none;
    }
    span{
      height:24px;
      line-height:24px;
    }
    &:hover{
      .icon{
        display: inline;
      }
    }
  }

</style>

